package general;

public class Val_Array extends Functional_Unit{

    private int[] array; //holds the split-up version of the value

    //
    //default constructor
    //
    public Val_Array () {
        array = new int[0]; //default array is empty
        splitVal(0); //default value is 0
    }

    //
    //regular constructor
    //
    public Val_Array (int input) {
        array = new int[getDim()];   //there will be dim entries in the array
        splitVal(input);
    }

    //
    //split a value into array entries
    //
    public void splitVal (int value) {
        int i;
        int mask = createMask();
        
        //for each entry of the array
        for(i = 0; i < array.length; i++) {
            //shift in m bits, from LSB to MSB
            array[i] = (value >> i * getM()) & mask;
        }
    }

    //
    //return the value array
    //Note: this might not make sense, use printValArray
    //
    public int[] getValArray () {
        return array;
    }

    //
    //set the value array
    //Note: this might not make sense, use splitVal
    //
    public void setValArray (int[] val) {
        this.array = val;
    }

    //
    //print out each array entry separately
    //Note: MSB -> LSB
    //
    public void printValArray () {
        int i;
        
        //for each entry of the array
        for(i = 0; i < array.length; i++) {
            //shift in m bits, from LSB to MSB
            System.out.print(array[i]);
        }
        
        System.out.print('\n');
    }

    //
    //convert the array value to an integer
    //Note: this only works for arrays with 32 bits or less, two's complement
    //
    public int toInt () {
        int value = 0;
       
        for(int i = 0; i < array.length; i++) {
            value = value | (array[i] << i * getM());
        }
        
        return value;
    }
    
    //
    //masks out all of the bits that don't fit in this granularity
    //Note: used by splitVal only
    //
    private int createMask () {
        return (int)Math.pow(2, getM()) - 1;
    }

}

